import {
  Box,
  FieldEffect,
  Icon,
  useCall,
  usePubSub,
  usePubSubState,
  useSimpleMemo,
  useTableActions,
  useTableColumns,
  useWillMountEffect,
} from '@/components';
import { FORM_ITEM_KEYS } from '@/constants/componentKeys';
import { pick, uid } from '@/utils';
import { pull } from '@/utils/fp';
import { Button, Table } from 'antd';
import React, { useMemo } from 'react';
import RuleConfigModal from './RuleConfigModal';

function DroolsRulesField(props) {
  const pubsub = usePubSub();
  const state = usePubSubState(pubsub);

  useWillMountEffect(pubsub.sub, console.log);

  const [itemProps] = useSimpleMemo(pick(props, FORM_ITEM_KEYS));

  const columns = useMemo(
    () => [
      { dataIndex: 'ruleSentence', title: '公式', ellipsis: true },
      // { dataIndex: 'msgCode', title: '返回信息', ellipsis: true, dict: 'prompt_pool' },
    ],
    [],
  );
  const actions = useMemo(
    () => ({
      edit: {
        dialog: RuleConfigModal,
        text: <Button size='small' type='link' icon={<Icon type='edit' />} />,
        itemProp: 'item',
      },
      del: {
        confirm: void 0,
        text: <Button size='small' type='link' icon={<Icon type='delete' />} />,
      },
    }),
    [],
  );

  const propsForCol = {
    onEdit(row, index, data) {
      const newState = state.slice();
      newState.splice(index, 1, data);
      pubsub.update(newState);
    },
    onDel(row) {
      pubsub.update(pull(row)(state));
    },
  };

  const tableColumns = useSimpleMemo([
    ...useTableColumns(columns),
    ...useTableActions(actions, propsForCol, { width: 80 }),
  ]);

  const onAdd = useCall((data) => {
    pubsub.update([...(state ?? []), { id: uid(), ...data }]);
  });

  return (
    <>
      <FieldEffect {...itemProps} pubsub={pubsub} />
      <Box>
        <RuleConfigModal onOk={onAdd}>
          <Button type='primary'>+ 新 增</Button>
        </RuleConfigModal>
        <Box py={2} />
      </Box>
      <Table pagination={false} rowKey='id' columns={tableColumns} dataSource={state} />
    </>
  );
}

export default DroolsRulesField;
